// pages/chooseAddress/chooseAddress.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: [], //收貨地址列表
    addressLength: true, //是否有收貨地址
  },
  //点击添加收货地址
  toAddress(e) {
    app.checkUserInfoAuthorizationCart().then(() => {
      let newsId = e.currentTarget.dataset.news;
      wx.navigateTo({
        url: `/page/detail/pages/addAddress/addAddress?id=${newsId}`
      })
    })

  },
  // 点击我的收货地址列表
  relocation(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let addressData = that.data.addressList[index];
    let location = {
      latitude: addressData.latitude,
      longitude: addressData.longitude,
      send_address_name: addressData.address,
      addressId: that.data.addressList[index].address_id
    }
    app.globalData.addressId = location.addressId
    wx.navigateBack({
      delta: -1
    })
  },

  onLoad: function (options) {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    const token = app.globalData.token;
    let json = {
      token: token,
    }
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.chooseAddress, jsonData).then(data => {
      that.setData({
        hiddenLoading: true
      })
      if (data.status == 1) {
        that.removeJoint(data)
        that.setData({
          addressList: data.result.address_data,
        })
      }
    }).catch(err => {
      app.showInfo(err.toString());
      that.setData({
        hiddenLoading: true
      })
    })
  },
  removeJoint(data) {
    data.result.address_data.map((res) => {
      if (res.is_default == 1) {
        res.isDefault = false;
      } else {
        res.isDefault = true;
      }
      let arr = res.address.split('|');
      res.address = (arr[0] || '') + (arr[1] || '')
    })
  },
})